package top.infopub.mgr.cap.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.*;
import top.infopub.mgr.cap.domain.LookInfoDomain;
import top.infopub.mgr.cap.dto.LookInfoDto;
import top.infopub.mgr.cap.jsonvo.CapLookInfoJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LookInfoService;
import top.infopub.mgr.cap.vo.LookInfoBeginVo;
import top.infopub.mgr.cap.vo.LookInfoVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.dao.ProjectInfoDao;
import top.infopub.mgr.mkt.dao.ProjectSubInfoDao;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.vo.BaseLineVo;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class LookInfoServiceImpl extends GenericServiceImpl<LookInfo, String> implements LookInfoService {

    @Autowired
    private LookInfoDao lookInfoDao;

    @Autowired
    private LookInfoAttDao lookInfoAttDao;

    @Autowired
    private LookInfoBankDao lookInfoBankDao;

    @Autowired
    private LookBankSubDao lookBankSubDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private LookInfoBeginDao lookInfoBeginDao;

    @Autowired
    private LookInfoBeginBankDao lookInfoBeginBankDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;

    @Autowired
    private BaseLineService baseLineService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Override
    public GenericDao<LookInfo, String> getDao() {
        return lookInfoDao;
    }

    @Override
    public Page<LookInfoDomain> selectByDomainWhere(Page<LookInfoDomain> page,
                                                    LookInfoBeginVo lookInfoBeginVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(lookInfoBeginVo.getDates())) {
            String[] splitTime = lookInfoBeginVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                lookInfoBeginVo.setEndDate(format.parse(splitTime[1]));
                lookInfoBeginVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LookInfoDomain>)lookInfoDao.selectByDomainWhere(lookInfoBeginVo);
    }

    @Override
    public Page<LookInfoDomain> selectMyCheckByDomainWhere(Page<LookInfoDomain> page,
                                                           LookInfoVo lookInfoVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LookInfoDomain>)lookInfoDao.selectMyCheckByDomainWhere(lookInfoVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLookInfo(LookInfo lookInfo, List<LookBankSub> lookBankSubs,
                             List<LookInfoAtt> lookInfoAtts, List<LookInfoBank> lookInfoBanks) {
        //执行新增
        //插入融资尽调记录
        lookInfoDao.insertById(lookInfo);

        //批量插入融资尽调对接金融机构
        if (CollectionUtils.isNotEmpty(lookInfoBanks)) {
            lookInfoBankDao.insertByBatch(lookInfoBanks);
        }

        //批量插入融资尽调对接金融机构子表
        if (CollectionUtils.isNotEmpty(lookBankSubs)) {
            lookBankSubDao.insertByBatch(lookBankSubs);
        }

        //批量插入融资尽调附件
        if (CollectionUtils.isNotEmpty(lookInfoAtts)) {
            lookInfoAttDao.insertByBatch(lookInfoAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.CAP_LOOK_INFO;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, lookInfo.getId(), lookInfo.getProcessId(), null);
    }

    @Override
    public LookInfoDto queryDetailById(String id) {

        LookInfoDto lookInfoDto = new LookInfoDto();
        //尽调信息
         LookInfo lookInfo = lookInfoDao.selectById(id);
        //详情信息
        lookInfoDto = lookInfoDao.queryDetailById(id);
        //查找金融机构
        List<LookInfoBank> lookInfoBanks = lookInfoBankDao.selectByProCode(lookInfo.getProCode());
        if (lookInfoBanks == null || lookInfoBanks.size() <= 0) {
            //如果金融机构为空，带出初调的金融机构信息
            List<LookInfoBeginBank> list = lookInfoBeginBankDao.selectByProCode(lookInfo.getProCode());
            if (list != null && list.size() > 0) {
                lookInfoBanks = new ArrayList<>();
                LookInfoBank lib;
                for (LookInfoBeginBank libb : list) {
                    lib = new LookInfoBank();
                    BeanUtils.copyProperties(libb, lib);
                    lookInfoBanks.add(lib);
                }
            }
        }
        lookInfoDto.setLookInfoBanks(lookInfoBanks);
        //如果尽调更改了入库情况 优先取尽调
        if (StringUtils.isNotBlank(lookInfo.getIsInStore())){
            lookInfoDto.setIsInStore(lookInfo.getIsInStore());
        }
        //附件
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(lookInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE46.getCode(), null);
        lookInfoDto.setFileAtt(fileAttaListToArray(attachmentList));
        //查询项目投资组成
        ProjectInfo byProCode = projectInfoDao.findByProCode(lookInfo.getProCode());
        lookInfoDto.setDeviceCost(byProCode.getDeviceCost());
        lookInfoDto.setRowSum(byProCode.getRowSum());
        lookInfoDto.setOtherCost(byProCode.getOtherCost());
        lookInfoDto.setInReadyCost(byProCode.getInReadyCost());
        lookInfoDto.setPeriodInterest(byProCode.getPeriodInterest());
        lookInfoDto.setSumAmount(byProCode.getSumAmount());
//        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(lookInfo.getProCode());
//        List<InvestmentInfoVo> investmentInfoVos = JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class);
//        for (InvestmentInfoVo investmentInfoVo : investmentInfoVos) {
//            if (StandardEnum.SHEBEI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setDeviceCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.GET_JIANAN.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setRowSum(investmentInfoVo.getTotal());
//            }else if (StandardEnum.GONGCHENG.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setOtherCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.YUBEI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setInReadyCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.JIANSHE.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setPeriodInterest(investmentInfoVo.getTotal());
//            }else if (StandardEnum.HEJI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setSumAmount(investmentInfoVo.getTotal());
//            }
//        }
        //底线标准情况
        List<BaseLineVo> baseLineVos = baseLineService.checkIsSatisfy(lookInfo.getProCode());
        lookInfoDto.setBaseLineVos(baseLineVos);
        return lookInfoDto;
    }

    @Override
    public RspVo saveAll(CapLookInfoJsonVo vo, AuthorizationVO userDtl, List<ProjectAttachment> attachmentList, Integer submitType, String bodyStr) {

        //尽调信息
        LookInfo lookInfo = new LookInfo();
        BeanUtils.copyProperties(vo.getLookInfoDto(),lookInfo);
        LookInfo lookInfo1 = lookInfoDao.selectById(lookInfo.getId());
        if (lookInfo1!=null &&
           StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(),lookInfo1.getProcessStatus())
            || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(),lookInfo1.getProcessStatus())
        ){
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }
        lookInfo.setUptBy(userDtl.getId());
        lookInfo.setUptTime(new Date());
        lookInfoDao.updateById(lookInfo);
        //金融信息
        //查询初调id
//        LookInfoBegin lookInfoBegin = lookInfoBeginDao.selectByProCode(lookInfo.getProCode());
        lookInfoBankDao.deleteByLookInfoId(lookInfo.getId());
        List<LookInfoBank> lookInfoBanks = vo.getLookInfoBanks();
        for (LookInfoBank lookInfoBank : lookInfoBanks) {
            lookInfoBank.setId(IdFactory.getUUIDUpper());
            lookInfoBank.setLookInfoId(lookInfo.getId());
            lookInfoBank.setProCode(lookInfo.getProCode());
            lookInfoBank.setAddBy(userDtl.getId());
            lookInfoBank.setAddTime(new Date());
        }
        lookInfoBankDao.insertByBatch(lookInfoBanks);
        //附件信息
        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(lookInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE46.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(lookInfo.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType==2){
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE3,bodyStr,lookInfo.getId(),lookInfo.getProCode(),userDtl);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public LookInfo selectBySguid(String id) {
        return lookInfoDao.selectById(id);
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
}
